package com.wgt.startx.util;


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by wgt on 2017/7/29.
 */
public class PropUtils {
    private static final Logger logger = LoggerFactory.getLogger(PropUtils.class);

    /**
     * 加载属性文件
     */
    public static Properties loadProps(String propertiesPath){
        Properties props = new Properties();
        InputStream is = null;
        try {
            if (StringUtils.isEmpty(propertiesPath)) {
                throw new IllegalArgumentException();
            }
            String suffix = ".properties";
            if (propertiesPath.lastIndexOf(suffix) == -1) {
                propertiesPath += suffix;
            }
            is = SmartClassUtil.getClassLoader().getResourceAsStream(propertiesPath);
            if (is != null) {
                props.load(is);
            }
        } catch (Exception e) {
            logger.error("加载属性文件出错！", e);
            throw new RuntimeException(e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                logger.error("释放资源出错！", e);
            }
        }
        return props;
    }




    /**
     * 获取字符型属性
     */
    public static String getString(Properties props, String key) {
        String value = "";
        if (props.containsKey(key)) {
            value = props.getProperty(key);
        }
        return value;
    }

    /**
     * 获取字符型属性（带有默认值）
     */
    public static String getString(Properties props, String key, String defalutValue) {
        String value = defalutValue;
        if (props.containsKey(key)) {
            value = props.getProperty(key);
        }
        return value;
    }

}
